package com.yonyou.gmmc.service.pointactivity.service;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.log4j.Logger;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dms.http.HttpCommonUtil;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventPointActivityDTO;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.util.JsonUtils;
import org.marketing.common.util.MapConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.service.pointactivity.constant.PointActivityConstant;
import com.yonyou.gmmc.service.pointactivity.dao.TmOwnerCarRelationMapper;
import com.yonyou.gmmc.service.pointactivity.dao.TmPointsActivityLogMapper;
import com.yonyou.gmmc.service.pointactivity.dao.TmPointsActivityPackeMapper;
import com.yonyou.gmmc.service.pointactivity.dao.TmPotentialUserMapper;
import com.yonyou.gmmc.service.pointactivity.dao.TrUserOwnerMapper;
import com.yonyou.gmmc.service.pointactivity.dto.ResultBillDate;

@Transactional
@Service("pointActivityService")
public class PointActivityService {

	private Logger logger = Logger.getLogger(PointActivityService.class);

	@Value("${DCMS-url}")
	private String dcmsUrl;

	@Autowired
	private TmPotentialUserMapper tmPotentialUserMapper;

	@Autowired
	private TrUserOwnerMapper trUserOwnerMapper;

	@Autowired
	private TmOwnerCarRelationMapper tmOwnerCarRelationMapper;

	@Autowired
	private TmPointsActivityLogMapper tmPointsActivityLogMapper;
	
	@Autowired
	private TmPointsActivityPackeMapper tmPointsActivityPackeMapper;
	

	@Autowired
	private BaseService eventService;
	
	/**
	 * 销售活动数组
	 */
	private static Long ACT_01 = 1000000001l;
	private static Long ACT_02 = 1000000002l;

	/**
	 * 获取结果Map
	 * 
	 * @param openId
	 * @return
	 */
	public Map<String, Object> getResultMap(String openId) throws Exception {

		Map<String, Object> resultMap = new HashMap<>();

		resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
		resultMap.put(ResultMsgConstants.QUERY_DATA, JsonUtils.map2JsonObject(checkOpenIdPower(openId)).toString());

		return resultMap;
	}

	/**
	 * 获取抽奖结果Map
	 * 
	 * @param openId
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public synchronized Map<String, Object> getPointReward(String openId) throws Exception {

		Map<String, Object> resultMap = new HashMap<>();

		Map<String, Object> map = checkOpenIdPower(openId);

		Map<String, Object> pointMap = new HashMap<>();

		if (map!=null && map.containsKey("isRepeat")&& Boolean.parseBoolean(map.get("isRepeat").toString())) {
			resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
			resultMap.put(ResultMsgConstants.QUERY_DATA, JsonUtils.map2JsonObject(map).toString());
			return resultMap;
		}
		
		if (map!=null && map.containsKey("isVinRepeat")&&Boolean.parseBoolean(map.get("isVinRepeat").toString())) {
			resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
			resultMap.put(ResultMsgConstants.QUERY_DATA, JsonUtils.map2JsonObject(map).toString());
			return resultMap;
		}
		// 是车主
		if (map!=null && map.get("userType")!=null && Integer.valueOf(map.get("userType").toString()) == PointActivityConstant.USER_TYPE_3.intValue()) {
			// 有可参加的活动
			if (map.containsKey("activityType") && Integer.valueOf(map.get("activityType").toString()) != PointActivityConstant.ACTIVITY_TYPE_0.intValue()
					&&map.containsKey("activityIsStart") && Boolean.parseBoolean(map.get("activityIsStart").toString())
					&&map.containsKey("activityIsEnd") && Boolean.parseBoolean(map.get("activityIsEnd").toString())
					&&map.containsKey("surplusPacke") && Boolean.parseBoolean(map.get("surplusPacke").toString())) {

				Map<String,Object> packeMap = getRewardPoint(Integer.valueOf(map.get("activityType").toString()));
				if(null != packeMap){
					
					Integer getPoint = Integer.valueOf(packeMap.get("POINT").toString());
					// 礼包数量
					updateUsCnt(Long.valueOf(packeMap.get("ID").toString()));
					
					pointMap.put("getPointStatus", "success");
					pointMap.put("getPoint", getPoint);
					pointMap.put("openId", openId);
					pointMap.put("userId", map.get("userId"));

					// 记录到表
					Map<String, Object> saveMap = new HashMap<>();
					saveMap.put("getPoint", getPoint);
					saveMap.put("vin", map.get("vin"));
					saveMap.put("userId", map.get("userId"));
					saveMap.put("pointsActivityId", map.get("pointsActivityId"));
					saveMap.put("openId", openId);
					saveMap.put("packeId", packeMap.get("ID"));

					tmPointsActivityLogMapper.saveAddPoint(saveMap);

					BizEvent event = new BizEvent();
					event.setEventBizType(EventBizType.POINT_ACTIVITY);
					event.setEventBizStep(EventBizStep.POINT_ACTIVITY_GET_POINT);
					EventPointActivityDTO dto = new EventPointActivityDTO();
					dto.setChangeNum(Long.valueOf(getPoint));
					dto.setUserId(Integer.valueOf(map.get("userId").toString()));
					event.setEventData(MapConverUtil.PO2Map(dto));
					eventService.sendEvent2MQ(event);

					resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
					resultMap.put(ResultMsgConstants.QUERY_DATA, JsonUtils.map2JsonObject(pointMap).toString());
				} else {
					map.put("getPointStatus", "fail");
					resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
					resultMap.put(ResultMsgConstants.QUERY_DATA, JsonUtils.map2JsonObject(map).toString());
				}
			} else {
				resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
				resultMap.put(ResultMsgConstants.QUERY_DATA, JsonUtils.map2JsonObject(map).toString());
			}
		} else {
			resultMap.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
			resultMap.put(ResultMsgConstants.QUERY_DATA, JsonUtils.map2JsonObject(map).toString());
		}

		return resultMap;
	}

	/**
	 * 获取积分
	 * @param integer 
	 * @return
	 */
	
	public Map<String, Object> getRewardPoint(Integer type) {

		List<Map<String, Object>> list = tmPointsActivityPackeMapper.queryPackeByActivityId(type == 1 ? ACT_01 : ACT_02);

		if (list.size() > 0) {
			Random random = new Random();
			int x = random.nextInt(list.size());
			return list.get(x);
		} else {
			return null;
		}
	}
	
	public void updateUsCnt(Long id){
		tmPointsActivityPackeMapper.updatePackeById(id);
	}

	/**
	 * 根据 openid 判断是否为车主、会员、粉丝（即判断是否符合抽奖活动的车主）
	 * 
	 * @author liyujiao
	 * @date 2017年5月3日
	 * @param openId
	 * @return
	 */
	public Map<String, Object> checkOpenIdPower(String openId){

		Map<String, Object> map = new HashMap<>();

		if (checkRepeat(openId)) {

			Map<String, Object> potentialMap = queryPotentialUser(openId);

			Map<String, Object> memberMap = null != potentialMap ? queryMemberInfo(potentialMap.get("POTENTIAL_USER_ID").toString()) : null;

			Map<String, Object> vehcileMap = null != memberMap ? queryVehcile(memberMap.get("USER_ID").toString()) : null;

			Integer userType = returnTypeByOpenId(potentialMap, memberMap, vehcileMap);

			if (userType == PointActivityConstant.USER_TYPE_3.intValue() && vehcileMap!=null && vehcileMap.get("VIN")!=null) {
				
				if (checkVinRepeat(vehcileMap.get("VIN").toString())) {

					Map<String, Object> param = new HashMap<>();
					param.put("vin", vehcileMap.get("VIN"));

					logger.info("PointActivityService To DCMS Url:" + PointActivityConstant.CARINFO_URL.replaceAll("dcmshost", dcmsUrl));
					List<ResultBillDate> result = null;
					try {
						result = HttpCommonUtil.getOwnerInfo(param, "IC011", PointActivityConstant.CARINFO_URL.replaceAll("dcmshost", dcmsUrl), ResultBillDate.class);
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}

					if (null != result) {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						map.put("userType", userType);
						map.put("vin", vehcileMap.get("VIN"));
						map.put("billDate", sdf.format(result.get(0).getBillDate()));
						map.put("authenticateDate", sdf.format(vehcileMap.get("VEHICLE_DATE")));

						map.put("activityType", returnActivityType(map));

						if (Integer.valueOf(map.get("activityType").toString()) != PointActivityConstant.ACTIVITY_TYPE_0.intValue()) {
							Map<String, Object> activityMap = trUserOwnerMapper.queryPointsActivity(map).get(0);
							map.put("activityIsStart", activityMap.get("ACTIVITY_DATE_START"));
							map.put("activityIsEnd", activityMap.get("ACTIVITY_DATE_END"));
							map.put("pointsActivityId", activityMap.get("POINTS_ACTIVITY_ID"));
							map.put("surplusPacke", activityMap.get("SURPLUS_PACKE"));
							map.put("userId", memberMap.get("USER_ID"));
						}

					} else {
						map.put("userType", PointActivityConstant.USER_TYPE_4);
					}
					map.put("openId", openId);
				} else {
					map.put("isVinRepeat", true);
				}
			} else {
				map.put("userType", userType);
			}

		} else {
			map.put("isRepeat", true);
		}

		return map;
	}

	/**
	 * 返回活动类型
	 * 
	 * @return
	 */
	public Integer returnActivityType(Map<String, Object> param) {

		List<Map<String, Object>> allActivityList = trUserOwnerMapper.queryPointsActivity(param);

		for (Map<String, Object> map : allActivityList) {

			boolean bill_check_s = Boolean.parseBoolean(map.get("BILL_DATE_START").toString());
			boolean bill_check_e = Boolean.parseBoolean(map.get("BILL_DATE_END").toString());
			boolean authenticate_check_s = Boolean.parseBoolean(map.get("AUTHENTICATE_DATE_START").toString());
			boolean authenticate_check_e = Boolean.parseBoolean(map.get("AUTHENTICATE_DATE_END").toString());

			if (bill_check_s && bill_check_e && authenticate_check_s && authenticate_check_e) {
				return Integer.valueOf(map.get("ACTIVITY_TYPE").toString());
			}
		}
		return PointActivityConstant.ACTIVITY_TYPE_0;
	}

	/**
	 * 根据三个map判断是车主还是粉丝还是会员
	 * 
	 * @param potentialMap
	 * @param memberMap
	 * @param vehcileMap
	 * @return
	 */
	public Integer returnTypeByOpenId(Map<String, Object> potentialMap, Map<String, Object> memberMap, Map<String, Object> vehcileMap) {

		return null != potentialMap ? null != memberMap ? null != vehcileMap ? PointActivityConstant.USER_TYPE_3 : PointActivityConstant.USER_TYPE_2 : PointActivityConstant.USER_TYPE_1 : PointActivityConstant.USER_TYPE_0;
	}
	
	/**
	 * 判断是否重复参加
	 * @param openId
	 * @return
	 */
	private boolean checkRepeat(String openId) {
		Map<String,Object> map = tmPointsActivityLogMapper.queryActivityByOpenId(openId);
		return null != map ? false : true; 
	}
	
	/**
	 * 判断车辆是否重复参加
	 * @param openId
	 * @return
	 */
	private boolean checkVinRepeat(String vin) {
		Map<String,Object> map = tmPointsActivityLogMapper.queryActivityForVinByOpenId(vin);
		return null != map ? false : true; 
	}

	/**
	 * 查询潜客
	 * 
	 * @param openId
	 * @return
	 */
	public Map<String, Object> queryPotentialUser(String openId) {
		return tmPotentialUserMapper.queryPotentialUserByOpenId(openId);
	}

	/**
	 * 查询会员
	 * 
	 * @param potentialUserId
	 * @return
	 */
	public Map<String, Object> queryMemberInfo(String potentialUserId) {
		return trUserOwnerMapper.queryMemberInfoByPotentialUserId(potentialUserId);
	}

	/**
	 * 查询车辆
	 * 
	 * @param userId
	 * @return
	 */
	public Map<String, Object> queryVehcile(String userId) {
		return tmOwnerCarRelationMapper.queryVehcileByMemberId(userId);
	}

}
